package com.lh.controller;

import com.lh.pojo.Users;
import com.lh.pojo.bo.UserBO;
import com.lh.service.PassportService;
import com.lh.utils.CookieUtils;
import com.lh.utils.IMOOCJSONResult;
import com.lh.utils.JsonUtils;
import com.lh.utils.MD5Utils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @program: foodie-dev
 * @description:
 * @author: LH
 * @create: 2022-04-01 16:17
 **/
@RestController
@RequestMapping("/passport")
@Api(value = "注册登录", tags = {"用于注册登录的相关api接口"})
public class PassportController {

    private static final Logger LOG = LoggerFactory.getLogger(PassportController.class);

    @Autowired
    private PassportService passportService;

    @ApiOperation(value = "退出登录", notes = "退出登录", httpMethod = "POST",
            response = IMOOCJSONResult.class,
            produces = MediaType.APPLICATION_JSON_VALUE)
    @PostMapping("/logout")
    public IMOOCJSONResult logout(@RequestParam String userId,
                                  HttpServletRequest request,
                                  HttpServletResponse response){

        // 清除用户的相关信息的cookie
        CookieUtils.deleteCookie(request,response,"user");

        //TODO 用户推出登录，需要清空购物车
        //TODO 分布式会话中需要清除用户数据

        return IMOOCJSONResult.ok();
    }

    @GetMapping("/usernameIsExist")
    @ApiOperation(value = "判断用户名是否已存在", notes = "判断用户名是否已存在", httpMethod = "GET",
            response = IMOOCJSONResult.class,
            produces = MediaType.APPLICATION_JSON_VALUE)
    public IMOOCJSONResult usernameIsExist(@RequestParam String username) {

        if (StringUtils.isEmpty(username)) {
            return IMOOCJSONResult.errorMsg("用户名为空");
        }

        boolean isExist = passportService.usernameIsExist(username);
        if (isExist) {
            return IMOOCJSONResult.ok();
        }

        return IMOOCJSONResult.errorMsg("用户名已存在");
    }

    @ApiOperation(value = "注册用户", notes = "注册用户", httpMethod = "POST",
            response = IMOOCJSONResult.class,
            produces = MediaType.APPLICATION_JSON_VALUE)
    @PostMapping("/register")
    public IMOOCJSONResult register(@RequestBody UserBO userBO,
                                    HttpServletRequest request,
                                    HttpServletResponse response) {

        String username = userBO.getUsername();
        String password = userBO.getPassword();
        String confirmPassword = userBO.getConfirmPassword();

        //1.判断用户名和密码是否为空
        if (StringUtils.isEmpty(username) ||
                StringUtils.isEmpty(password) ||
                StringUtils.isEmpty(confirmPassword)) {
            return IMOOCJSONResult.errorException("用户名或者密码为空!");
        }

        //2.判断用户名是否已存在
        boolean isExist = passportService.usernameIsExist(username);
        if (!isExist) {
            return IMOOCJSONResult.errorException("用户名已存在!");
        }

        //3.判断密码是否小于六位
        if (password.length() < 6) {
            return IMOOCJSONResult.errorException("密码小于六位数!");
        }

        //4.判断两次密码是否相同
        if (!password.equals(confirmPassword)) {
            return IMOOCJSONResult.errorException("两次密码不同!");
        }

        //5.注册
        Users user = passportService.createUser(userBO);

        user = setUserNULL(user);

        CookieUtils.setCookie(request, response, "user", JsonUtils.objectToJson(user), true);

        //TODO 生成用户token，存入redis会话
        //TODO 同步购物车数据

        return IMOOCJSONResult.ok();

    }

    @ApiOperation(value = "用户登录", notes = "用户登录", httpMethod = "POST",
            response = IMOOCJSONResult.class,
            produces = MediaType.APPLICATION_JSON_VALUE)
    @PostMapping("/login")
    public IMOOCJSONResult login(@RequestBody UserBO userBO,
                                 HttpServletRequest request,
                                 HttpServletResponse response) throws Exception {

        //1. 登录
        Users user = passportService.getUserByNameAndPassword(userBO.getUsername(), MD5Utils.getMD5Str(userBO.getPassword()));
        if (user == null) {
            return IMOOCJSONResult.errorMsg("用户或密码输入错误!");
        }

        user = setUserNULL(user);

        CookieUtils.setCookie(request, response, "user", JsonUtils.objectToJson(user), true);

        //TODO 生成用户token，存入redis会话
        //TODO 同步购物车数据

        return IMOOCJSONResult.ok(user);

    }

    private Users setUserNULL(Users users) {
        users.setCreatedTime(null);
        users.setEmail(null);
        users.setSex(null);
        users.setBirthday(null);
        users.setRealname(null);
        users.setPassword(null);

        return users;
    }
}
